package com.huizu.pay.util;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.transaction.annotation.Transactional;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.wxpay.sdk.WXPay;

import net.sf.json.JSONObject;

public class PayInterface {

	// 支付包
	private static String app_id = "2021002179632077";// appId
	private static String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn8GIeM0AVeIpDQRJvb9yC9xwI4+A49aP0Rxxl+we4F+e5icDRL3W0afO/YI0cYgl3bdipAwvkUPWhtTuTmaxFJa/fBu6LOEbyqQVUvsyRFJwoY1PPOUK+HTrfs2CHJ3itCp0heWePBKjAXRNWaskswcTRgTL1A+h9Qx+EbHWf2f1yTrakF7OiXIaM6+e5W+A8Ey38T3PhIB3lqeby0zpHON3Tqyn6FB2kNFssj3yvRu2PvRnc0TptvM+mY3Nijynaid/nFwGWzzZ7fuRVHG8GpW4lOsHYLNdCJibJFVqIwbLYsoa7Gp8xhrTvufUxQyygUOmxIArFvEXmTbZy/S8nwIDAQAB";
	private static String merchant_private_key = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCtwDKUgRNBL0IT29Ti+wH53ILVel4IMlWKputtPI4TeSucM++RdGIXwdRiPJiCWe4xhf3v9q6AVp/3mpq9BW2Ha7tzq31IYlHAfk/iVw66gqzyIkUMdp8KDMb+42jSGggOOYJRs/oSt9BBksEWBX44G6KAUD70/wCK0jnDur5msWLWYJ3fd03SoLTq7yOeAx8DZT23HvTqLi4EW6vfu/u/sG7cW3x5aRALiIQsCkFCoh1rCZoxpqkJW0eWbyn+vCVN+1QceBQyobPV4vdwPVssmCX7AZD+gfyx+P80udHff6Qe5zbizwyU1DjzrQOaQzCgqHiuDQo621eW0wQ2wxDLAgMBAAECggEAGSFub2pH5aq3LPYj0XyqqYAKcGQVi6v0EWzZKmCS0CA7fYlJgklKEtOXK2pGSLxHJmSR+Q496RQeaQq0jNhnIioj37QTF9AYsPXUChG7cKCL8S2hvQ6/LA3zDlTICXN4bM5Gmhik9+YcOg/G26+JtQXSOCrjID5tzqZfcn7lIScTo15ECWnf+M9jbwHPfGtEIrsqeJ462dVCJMYN1fHQ2RleoBo0RKAdk+HqBQ+z5+xrmMhM8W9hoWig6W1NNPMgtcDSRURrx0sDuHpj3/Q3EHeweRS26GGv1kB1/3uvLm1aHte/zunEf8GyXmvRj2x7vpKsR4j3DYVis3we7h2yqQKBgQDqNUse0MflMaTlM2EpqowL1RcGsH4X8l7TH1A8MXmqfmiRX7B5duRdxyLoGDKfbWC9WQP8rPcq3519qDFjCJ1D9tXCaaIsVUZa4HJB3hg0QsBREQoOX5fYY4iXOsn23nUt3wRwlkjCQz9d3QYPdr6irYT+y1mYg8FIqaRLIfoVdQKBgQC96tfGM+BVyVKNMBuIuzBo0gOkmXJl+SFgS5XN087r+xVekWn+6MwY+aDI6O+B3eOJ5hx4f64x2MRlmQ4liIs95Zg9kbTLN8g2bi+V77H3Y7uOkRTeApTm0B51wF3PcSjpPYosgLaz7d23rdUpy5TjpERERVnmX2XjXhqXbIqFPwKBgH1vpZgPgcAC4qnO5s8GBJOhwP9YL3Br4tV4A+T5Koxhv2d8tGuZfZ2sNcnQi+xPDGzc7AG8MXTI5vSRzEGaL4BjBwFkyfKsiU3Kv+b/KD91MMM6OQSRtiWyyUkVt218n4290AbstnM0yQ9gfQpzMo62GHDOQGIqzq44DUIgJGyxAoGAcfzNK2ohgHvIL3OrYwKvCIrcouNylR/VV32mWRaCwIJADjWK//Nr5KWXSl78ud6a3j6d4fkIbWSkZDJcGkz8/daa7IFSmRJO+dRifUSTdV+HyAbuFl5ITsylK5mc9I//tRY5o4JRpmbjR4ZvRZmqMIN8cdmKHsotVi06Gp6L+XMCgYBfW1OlnceKu0Zuw5b41NTrxaAoqK+Em24ySCD5bapvUs5k0NM6L6DZUfjrvipJkg/WZ4vIHRnPo7Jo9A7W1OMKVQBRdrUoBU3Ga9/I7zYWZf/PDMNeksSi80mNnqY4PDa6Tujwmb8keZHUtLq8DgO2IS4etHdUQ1eKP5gnwWLQ3A==";

	// 微信
	private static String wx_app_appId = "wxd20b2a940ee3c182";
	private static String app_private_key = "f87c0d62eed166a6290ba22e918b5afe";
	private static String app_mch_id = "1614499944";
	private static String create_ip = "192.168.1.100";
	public static final String unifiedorder = "https://api.mch.weixin.qq.com/pay/unifiedorder";
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

	/**
	 * 支付宝预下单
	 *
	 * @param orderMap
	 * @return
	 */
	public static Map<String, Object> insertAlipayPay(Map<String, Object> orderMap) {
		Map<String, Object> payMap = new HashMap<>();
		try {
			String url = String.valueOf(orderMap.get("url"));
			if (orderMap != null && orderMap.size() > 0) {
				String price = orderMap.get("price").toString();
				AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, app_id,
						merchant_private_key, "json", AlipayConfig.charset, alipay_public_key, AlipayConfig.sign_type);
				// 拼个账单添加账单请勿重新值
				AlipayTradeAppPayRequest alipayRequest = new AlipayTradeAppPayRequest();
				AlipayTradeAppPayModel alipayTradeAppPayModel = new AlipayTradeAppPayModel();
				String notify_url = url;// 回调地址
				String orderCode = String.valueOf(orderMap.get("orderCode")); // 预下单订单编号
				alipayTradeAppPayModel.setBody("商品");
				alipayTradeAppPayModel.setSubject("商品");
				alipayTradeAppPayModel.setOutTradeNo(orderCode);
				alipayTradeAppPayModel.setTimeoutExpress("30m");
				alipayTradeAppPayModel.setTotalAmount(price);
				alipayTradeAppPayModel.setProductCode("FACE_TO_FACE_PAYMENT");// QUICK_MSECURITY_PAY
				alipayRequest.setBizModel(alipayTradeAppPayModel);
				alipayRequest.setNotifyUrl(notify_url);
				AlipayTradeAppPayResponse response = alipayClient.sdkExecute(alipayRequest);
				if (response.isSuccess()) {
					payMap.put("orderInfo", response.getBody());// 返回打印信息
					payMap.put("orderCode", orderCode);
					payMap.put("code", 0);
					payMap.put("msg", "预下单成功");
				}
			} else {
				payMap.put("code", 1);
				payMap.put("msg", "预下单失败");
			}
		} catch (AlipayApiException e) {
			payMap.put("msg", "预下单失败");
			payMap.put("code", 1);
			e.printStackTrace();
		}
		return payMap;
	}

	// 支付宝回调
	public static Map<String, Object> alipayNotifyUrl(HttpServletRequest request) {

		Map<String, String> params = new HashMap<>();
		Map<String, Object> orderMap = new HashMap<>();
		try {
			params = analysisParams(request);
			orderMap = new HashMap<String, Object>();
			boolean signVerified = AlipaySignature.rsaCheckV1(params, alipay_public_key, AlipayConfig.charset,
					AlipayConfig.sign_type);
			if (signVerified) {
				orderMap = getAlipayOrderCodeInfo(request);
				System.out.println(orderMap);
				if ("TRADE_SUCCESS".equals(orderMap.get("trade_status"))) {
					if (orderMap.containsKey("out_trade_no")) {
						orderMap.put("orderCode", orderMap.get("out_trade_no"));
						orderMap.put("code", 0);
					} else {
						orderMap.put("code", 1);
					}
				} else {
					orderMap.put("code", 1);
				}
			} else {
				orderMap.put("code", 1);
			}
		} catch (Exception e) {
			orderMap.put("code", 1);
			e.printStackTrace();
		}
		return orderMap;
	}

	/**
	 * 支付宝支付完成回调地址（异步回调） 校验支付宝是否真正支付成功
	 *
	 * @param request
	 */
	public static Map<String, String> analysisParams(HttpServletRequest request) throws UnsupportedEncodingException {
		Map<String, String> params = new HashMap<String, String>();
		Map<String, String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
		}
		return params;
	}

	// 支付宝退款
	public static int alipayRefund(String orderCode, String totalPrice) throws AlipayApiException {
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
				PayConstants.ALI_PAY_APP_ID, PayConstants.ALI_PAY_MERCHANT_PRIVATE_KEY, "json", "utf-8",
				PayConstants.ALI_PAY_PUBLIC_KEY, "RSA2"); // 获得初始化的AlipayClient
		AlipayTradeRefundModel refundModel = new AlipayTradeRefundModel();
		refundModel.setOutTradeNo(orderCode);
		refundModel.setRefundAmount(totalPrice);
		refundModel.setRefundReason("商品退款");
		AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
		request.setBizModel(refundModel);
		AlipayTradeRefundResponse response = alipayClient.execute(request);
		System.out.println(response.getMsg() + "\n");
		System.out.println(response.getBody());
		if ("Success".equals(response.getMsg()))
			return 0;
		else
			return 1;
	}

	/**
	 * 获取支付宝订单信息
	 *
	 * @param request
	 * @return
	 */
	public static Map<String, Object> getAlipayOrderCodeInfo(HttpServletRequest request) {
		Map<String, Object> orderMap = new HashMap<String, Object>();
		String out_trade_no = request.getParameter("out_trade_no");// 商户订单号
		String trade_no = request.getParameter("trade_no");// 支付宝交易号
		String total_amount = request.getParameter("total_amount");// 付款金额
		String timestamp = request.getParameter("timestamp");
		String trade_status = request.getParameter("trade_status");
		orderMap.put("out_trade_no", out_trade_no);
		orderMap.put("trade_no", trade_no);
		orderMap.put("total_amount", total_amount);
		orderMap.put("timestamp", timestamp);
		orderMap.put("trade_status", trade_status);
		return orderMap;
	}

	/// ======================微信=================================
	/**
	 * 微信app预下单
	 * 
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> insertWeChatPay(Map<String, Object> orderMap, HttpServletRequest request)
			throws Exception {
		MyAppConfig myAppConfig = new MyAppConfig();
		WXPay wxpay = new WXPay(myAppConfig);
		HashMap<String, Object> hashMap = new HashMap<>();
		SortedMap<String, Object> signMap = new TreeMap<>();// 生成签名信息
		Map<String, String> dataMap = new HashMap<>();// 微信订单信息
		Map<String, Object> payMap = new HashMap<>();// 接口返回信息
		String orderCode = String.valueOf(orderMap.get("orderCode"));
		String url = String.valueOf(orderMap.get("url"));
		String price = orderMap.get("price").toString();
		if (orderMap != null && orderMap.size() > 0) {
			try {
				String nonceStr = getNonceStr();// 随机字符串
				String spbillCreateIp = getClientIP(request);// 访问IP
				signMap = insertSignInfo(nonceStr);// 生成签名信息
				dataMap.put("appid", wx_app_appId);
				dataMap.put("mch_id", app_mch_id);
				dataMap.put("nonce_str", nonceStr);
				dataMap.put("body", "商品");
				dataMap.put("out_trade_no", orderCode);
				dataMap.put("total_fee", queryWxOrderPrice(price));
				dataMap.put("spbill_create_ip", spbillCreateIp);
				dataMap.put("notify_url", url);
				dataMap.put("trade_type", "APP");
				dataMap.put("sign", createSign(signMap, app_private_key));
				Map<String, String> resp = wxpay.unifiedOrder(dataMap);// 请求微信预支付接口，生成订单
				System.out.println(resp);
				if ("SUCCESS".equals(resp.get("result_code")) && "SUCCESS".equals(resp.get("return_code"))) {
					String appId = StringSplit.objectToString(resp.get("appid"));
					String mchId = StringSplit.objectToString(resp.get("mch_id"));
					String noncestr = StringSplit.objectToString(resp.get("nonce_str"));
					String prepayId = StringSplit.objectToString(resp.get("prepay_id"));
					long timeStamp = new Date().getTime() / 1000;// 当前时间戳
					signMap = insertSignInfoAgain(appId, mchId, prepayId, noncestr, timeStamp);// 生成签名信息
					hashMap.put("code", 0);
					hashMap.put("msg", "预下单成功");
					payMap.put("appId", appId);// 公众账号ID
					payMap.put("mchId", mchId);// 商户号
					payMap.put("nonceStr", noncestr);// 随机字符串
					payMap.put("prepayId", prepayId);// 预支付交易会话标识
					payMap.put("orderCode", orderCode);// 订单编号
					payMap.put("tradeType", StringSplit.objectToString(resp.get("trade_type")));// 交易类型
					payMap.put("sign", createSign(signMap, app_private_key));// 微信签名
					payMap.put("timeStamp", timeStamp);
					hashMap.put("data", payMap);
				}
			} catch (Exception e) {
				hashMap.put("code", 1);
				hashMap.put("msg", "预下单失败");
				e.printStackTrace();
			}
		}
		return hashMap;
	}

	// 微信小程序支付
	public Map<String, Object> payOrder(Map<String, Object> pm) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		SortedMap<String, Object> parameters = new TreeMap<String, Object>();
		String totalPrice = queryWxOrderPrice(String.valueOf(pm.get("price")));
		String url = String.valueOf(pm.get("url"));
		parameters.put("appid", wx_app_appId);
		parameters.put("mch_id", app_mch_id);
		parameters.put("nonce_str", getNonceStr());// 签名
		parameters.put("body", "商品");// 商品描述
		parameters.put("out_trade_no", String.valueOf(pm.get("orderCode")));// 订单号
		parameters.put("total_fee", totalPrice);// 金额
		parameters.put("spbill_create_ip", create_ip);// 终端IP
		parameters.put("notify_url", url);// 回调地址
		parameters.put("trade_type", "JSAPI");
		parameters.put("openid", String.valueOf(pm.get("openId")));
		parameters.put("sign", createSign(parameters, app_private_key));
		String result = postData(unifiedorder, getRequestXml(parameters));
		System.out.println(result);
		SortedMap<String, Object> rem = XmlUtil.doXMLParse(result);
		if ("SUCCESS".equals(rem.get("return_code").toString())
				&& "SUCCESS".equals(rem.get("result_code").toString())) {
			String prepay_id = rem.get("prepay_id").toString();
			createPackageValue(wx_app_appId, app_private_key, prepay_id);
			if (prepay_id != null && prepay_id.length() > 10) {
				ObjectMapper mapper = new ObjectMapper();
				String res = createPackageValue(wx_app_appId, app_private_key, prepay_id);
				map = mapper.readValue(res, Map.class);
				map.put("code", "0");
				map.put("msg", "预下成功");
			}
		} else {
			map.put("code", 1);
			map.put("msg", "预下单失败");
		}

		return map;
	}

	/**
	 * 微信支付完成回调地址
	 *
	 * @param request
	 * @param response
	 */
	@Transactional
	public static Map<String, Object> wxTradePagePayNotifyUrl(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Map<String, Object> map = new HashMap<>();
		String string;
		InputStream inputStream;
		StringBuffer stringBuffer = new StringBuffer();
		inputStream = request.getInputStream();
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
		while ((string = bufferedReader.readLine()) != null)
			stringBuffer.append(string);
		bufferedReader.close();
		inputStream.close();
		Map<String, Object> xmlMap = new HashMap<String, Object>();
		xmlMap = XmlUtil.doXMLParse(stringBuffer.toString());// 解析xml成map
		SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
		Iterator it = xmlMap.keySet().iterator();
		while (it.hasNext()) {
			String str = "";
			String parameter = (String) it.next();
			String parameterValue = String.valueOf(xmlMap.get(parameter));
			if (null != parameterValue)
				str = parameterValue.trim();
			packageParams.put(parameter, str);
		}
		if (PayCommonUtil.isTenpaySign("UTF-8", packageParams, app_private_key)) {
			String resXml = "";
			if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
				resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
						+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
				System.out.println("这是微信回调显示报文已成功");
				if (packageParams.containsKey("out_trade_no")) {
					String orderCode = (String) packageParams.get("out_trade_no");
					map.put("code", 0);
					map.put("orderCode", orderCode);
				}
			} else {
				System.out.println("这是微信支付失败");
				resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
						+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
				map.put("code", 1);
			}
			BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
			out.write(resXml.getBytes());
			out.flush();
			out.close();
		}
		return map;
	}

	// 退款
	public static int wxRefund(String orderCode, String totalFee, String refundFee) throws Exception {
		HashMap<String, String> map = new HashMap<>();
		MyAppConfig myAppConfig = new MyAppConfig();
		WXPay wxPay = new WXPay(myAppConfig);
		map.put("out_trade_no", orderCode);
		map.put("total_fee", queryWxOrderPrice(totalFee));
		map.put("refund_fee", queryWxOrderPrice(refundFee));
		map.put("out_refund_no", orderCode);
		Map<String, String> refund = wxPay.refund(map);
		if ("SUCCESS".equals(refund.get("return_code")) && "SUCCESS".equals(refund.get("result_code"))) {
			return 0;
		} else {
			return 1;
		}
	}

	/*
	 * 随机字符窜
	 */
	public static String getNonceStr() {
		String timeStamp = String.valueOf((new Date().getTime()));
		String randomStr = String.valueOf(new Random().nextInt(100000));
		String nonceStr = Md5Util.MD5Encode(timeStamp.concat(randomStr), "utf-8");
		int maxLength = nonceStr.length() > 32 ? 32 : nonceStr.length();
		return nonceStr.substring(0, maxLength);
	}

	// 分析IP
	public static String getClientIP(HttpServletRequest httpservletrequest) {
		if (httpservletrequest == null)
			return null;
		String s = httpservletrequest.getHeader("X-Forwarded-For");
		if (s == null || s.length() == 0 || "unknown".equalsIgnoreCase(s))
			s = httpservletrequest.getHeader("Proxy-Client-IP");
		if (s == null || s.length() == 0 || "unknown".equalsIgnoreCase(s))
			s = httpservletrequest.getHeader("WL-Proxy-Client-IP");
		if (s == null || s.length() == 0 || "unknown".equalsIgnoreCase(s))
			s = httpservletrequest.getHeader("HTTP_CLIENT_IP");
		if (s == null || s.length() == 0 || "unknown".equalsIgnoreCase(s))
			s = httpservletrequest.getHeader("HTTP_X_FORWARDED_FOR");
		if (s == null || s.length() == 0 || "unknown".equalsIgnoreCase(s))
			s = httpservletrequest.getRemoteAddr();
		if ("127.0.0.1".equals(s) || "0:0:0:0:0:0:0:1".equals(s))
			try {
				s = InetAddress.getLocalHost().getHostAddress();
			} catch (UnknownHostException unknownhostexception) {
				unknownhostexception.printStackTrace();
			}
		if (s.indexOf(",") != -1)
			s = s.substring(0, s.indexOf(","));
		return s;
	}

	/**
	 * 微信支付签名
	 *
	 * @param nonceStr
	 * @return
	 */
	private static SortedMap<String, Object> insertSignInfo(String nonceStr) {
		SortedMap<String, Object> signMap = new TreeMap<>();// 生成签名信息
		signMap.put("appid", wx_app_appId);
		signMap.put("mch_id", app_mch_id);
		signMap.put("nonce_str", nonceStr);
		return signMap;
	}

	// 微信元转分
	private static String queryWxOrderPrice(String orderMap) {
		// 元为单位 转换为分为单位
		// 元为单位 转换为分为单位
		BigDecimal orderPrice = new BigDecimal(String.valueOf(orderMap)).multiply(new BigDecimal(100));
		return orderPrice.setScale(0, BigDecimal.ROUND_HALF_UP).toString();// 订单金额
	}

	public static String createSign(SortedMap<String, Object> packageParams, String API_KEY) {
		StringBuffer sb = new StringBuffer();
		Set<Map.Entry<String, Object>> es = packageParams.entrySet();
		Iterator<Map.Entry<String, Object>> it = es.iterator();
		while (it.hasNext()) {
			Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
			Object ok = entry.getKey();
			String k = ok == null ? null : ok.toString();
			Object ov = entry.getValue();
			String v = ov == null ? null : ov.toString();
			if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + API_KEY);
		String sign = Md5Util.MD5Encode(sb.toString(), "utf-8").toUpperCase();
		return sign;
	}

	private static SortedMap<String, Object> insertSignInfoAgain(String appId, String mchId, String prepayId,
			String noncestr, long timeStamp) {
		SortedMap<String, Object> signMap = new TreeMap<>();// 生成签名信息
		signMap.put("appid", appId);
		signMap.put("partnerid", mchId);
		signMap.put("prepayid", prepayId);
		signMap.put("noncestr", noncestr);
		signMap.put("timestamp", timeStamp);
		signMap.put("package", "Sign=WXPay");
		return signMap;
	}

	public String getRequestXml(SortedMap<String, Object> parameters) {
		StringBuffer sb = new StringBuffer();
		sb.append("<xml>");
		Set<Entry<String, Object>> es = parameters.entrySet();
		Iterator<Entry<String, Object>> it = es.iterator();
		while (it.hasNext()) {
			Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
			Object ok = entry.getKey();
			String k = ok == null ? null : ok.toString();
			Object ov = entry.getValue();
			String v = ov == null ? null : ov.toString();
			if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
				sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
			} else {
				sb.append("<" + k + ">" + v + "</" + k + ">");
			}
		}
		sb.append("</xml>");
		return sb.toString();
	}

	public String postData(String urlStr, String data) {
		BufferedReader reader = null;
		try {
			URL url = new URL(urlStr);
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(5000);
			conn.setDoInput(true);
			OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
			if (data == null)
				data = "";
			writer.write(data);
			writer.flush();
			writer.close();

			reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
				sb.append("\r\n");
			}
			return sb.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (reader != null)
					reader.close();
			} catch (IOException e) {
			}
		}
		return null;
	}

	public String createPackageValue(String appid, String appKey, String prepay_id) {
		// 封装调用支付接口所需参数
		SortedMap<String, Object> nativeObj = new TreeMap<String, Object>();
		nativeObj.put("appId", appid);
		nativeObj.put("timeStamp", Long.toString(new Date().getTime() / 1000));// 时间戳
		// 生成随机数
		Random random = new Random();
		String data = String.valueOf(random.nextInt(10000));
		String randomStr = Md5Util.MD5Encode(data, "utf-8").toUpperCase();
		nativeObj.put("nonceStr", Md5Util.MD5Encode(randomStr, "utf-8").toLowerCase());// 随机字符串
		nativeObj.put("package", "prepay_id=" + prepay_id);// prepay_id
		nativeObj.put("signType", "MD5");//
		nativeObj.put("paySign", createSign(nativeObj, appKey));// 签名
		nativeObj.put("code", "0");
		nativeObj.put("msg", "签名成功");
		return JSONObject.fromObject(nativeObj).toString();
	}

}
